import {
    createAsyncThunk,
    createSlice
} from "@reduxjs/toolkit";
import {useSelector} from "react-redux";
import {message} from "antd";
import {getInfo, postLogin, postLogout} from "@/api/auth";

const authSlice = createSlice({
    name:"auth",
    initialState:{
        token:localStorage.getItem("token")?localStorage.getItem("token"):null,
        // userName:""
        avatar:localStorage.getItem("avatar")?localStorage.getItem("avatar"):null,
        name:localStorage.getItem("name")?localStorage.getItem("name"):null,
    },
    reducers:{
        upToken(state,{payload}){
            state.token = localStorage.token =  payload;
        },
        upInfo(state,{payload}){
            state.avatar = localStorage.avatar =  payload.avatar;
            state.name = localStorage.name =  payload.name;
        },
        clearInfo(state){
            localStorage.clear();// 清除所有的storage
            state.token = state.avatar = state.name = null;
        }

    },
    extraReducers(builders){
        builders.addCase(postLoginAsync3.fulfilled,(state,{payload})=>{
            // console.log("postLoginAsync3.fulfilled",payload)
            state.token = localStorage.token = payload.data.token;
        }).addCase(postLoginAsync3.rejected,(state,action)=>{
            console.log("postLoginAsync3.rejected",action)
        }).addCase(postLoginAsync3.pending,(state,{payload})=>{
            console.log("postLoginAsync3.pending","开始")
        })
    }
})
const {upToken,upInfo,clearInfo} = authSlice.actions;
export const useSelectorAuth = ()=>useSelector((state:any)=>state.auth);
export const postLoginAsync = (values:any)=>{
    return async ()=>{
        const res = await postLogin(values);
        return res;
    }
}
export const postLoginAsync2 = (values:any)=>{
    return async (dispatch:any)=>{
        const res:any = await postLogin(values);
        message.success(res.message);
        dispatch(upToken(res.data.token));
        return res;
    }
}
// 退出登陆
export const postLogoutAsync = ()=>{
    return async (dispatch:any)=>{
        const result = await postLogout();
        dispatch(clearInfo());
    }
}
// 创建异步action,用于获取用户详情
export const getInfoAsync = ()=>{
    return async (dispatch:any,getState:any)=>{
        const {auth} = getState();
        // if(auth.name) return;
        // const res= await getInfo();
        // dispatch(upInfo(res.data));
    }
}


// 1- 通过createAsyncThunk创建的函数运行的结果，可以作为dispatch接收的参数。
// 2- dispatch（postLoginAsync3（）），会执行createAsyncThunk3接收的第二个参数
// 3- 回调函数（createAsyncThunk3接收的第二个参数），返回的是一个Promise
// 4- promise成功：extraReducers-》postLoginAsync3.fulfilled
// 5- promise失败：extraReducers-》postLoginAsync3.rejected
export const postLoginAsync3 = createAsyncThunk("postLoginAsync3",async (values:any)=>{
    // throw "异常"
    // return 1;
    const res:any = await postLogin(values);
    message.success(res.message);
    return res;
})

export default authSlice.reducer;